package com.thread.threadpractice.utils;

import com.alibaba.excel.context.AnalysisContext;
import com.alibaba.excel.event.AnalysisEventListener;
import com.thread.threadpractice.domain.ProductExcel;
import com.thread.threadpractice.entity.Product;
import com.thread.threadpractice.service.ProductService;
import lombok.extern.slf4j.Slf4j;

import java.util.ArrayList;
import java.util.List;

@Slf4j
public class ExcelListener extends AnalysisEventListener<ProductExcel> {

    private final ProductService productService;

    private List<Product> cachedDataList = new ArrayList<>();

    public ExcelListener(ProductService productService) {
        this.productService = productService;
    }

    @Override
    public void invoke(ProductExcel data, AnalysisContext context) {//定义读取每行后的操作
        // 转换为数据库实体
        Product product = new Product();

        product.setTitle(data.getTitle())
                .setDescription(data.getDescription())
                .setPrice(data.getPrice())
                .setCategoryId(data.getCategoryId())
                .setCreateTime(data.getCreateTime())
                .setUpdateTime(data.getUpdateTime())
                .setIsDeleted(data.getIsDeleted())
                .setImages(data.getImages())
                .setSaleNum(data.getSaleNum())
                .setFavoriteNum(data.getFavoriteNum());

        cachedDataList.add(product);

    }

    @Override
    public void doAfterAllAnalysed(AnalysisContext context) {
        saveData();
        log.info("所有数据导入完成！");
    }

    private void saveData() {
        if (!cachedDataList.isEmpty()) {
            productService.insertBatch(cachedDataList);
            log.info("已保存 {} 条数据", cachedDataList.size());
        }
    }
}




